/*
 * Licensed to the Tai Ping Jin Ke
 *
 * Copyright (c) 2022 .
 * All rights reserved.
 * 项目名称：呼叫中心-通用处理层-任务调度
 * 版权说明：本软件属太平金融科技服务(上海)有限公司所有，在未获得太平金融科技服务(上海)有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.taiping.cc.job.manager.common;

import com.taiping.cc.application.constant.service.PlatformServiceEnum;
import com.taiping.cc.job.dataobject.HttpParamConfigDO;
import com.taiping.cc.job.dataobject.HttpRequestConfigDO;
import com.taiping.cc.job.dataobject.HttpResponseConfigDO;
import com.taiping.cc.job.converter.HttpParamConfigConverter;
import com.taiping.cc.job.converter.HttpRequestConfigConverter;
import com.taiping.cc.job.converter.HttpResponseConfigConverter;
import com.taiping.cc.job.manager.transaction.HttpServiceTransaction;
import com.taipingframework.utility.http.ServiceConfigInfo;
import com.taipingframework.utility.http.ServiceConfigInfo.ServiceRequestConfigInfo;
import com.taipingframework.utility.http.ServiceConfigInfo.ServiceResponseConfigInfo;
import com.taipingframework.utility.exception.ManagerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 部分通用的业务逻辑代码抽取出来放在manager层
 */
@Service
public class HttpServiceCommon {
    private HttpServiceTransaction httpServiceTransaction;

    @Autowired
    public void setHttpServiceTransaction(HttpServiceTransaction httpServiceTransaction) {
        this.httpServiceTransaction = httpServiceTransaction;
    }

    /**
     * 保存网络服务配置，不存在就新增，存在就更新
     */
    public void saveOrUpdateHttpServiceConfig(PlatformServiceEnum serviceConstant, ServiceConfigInfo serviceConfigInfo) throws ManagerException {
        try {
            ServiceRequestConfigInfo requestConfigInfo = serviceConfigInfo.getServiceRequestConfigInfo();
            ServiceResponseConfigInfo responseConfigInfo = serviceConfigInfo.getServiceResponseConfigInfo();

            // 网络服务请求配置
            HttpRequestConfigDO requestConfig = HttpRequestConfigConverter.convert(serviceConstant, requestConfigInfo);

            // 网络服务响应配置
            HttpResponseConfigDO responseConfig = HttpResponseConfigConverter.convert(serviceConstant, responseConfigInfo);

            // 网络服务参数配置
            List<HttpParamConfigDO> httpParamConfigList = HttpParamConfigConverter.convert(serviceConstant, serviceConfigInfo);

            // 所有的事务控制必须放在manager层，一来统一管理，二来异步注解和本地事务注解它们在底层都是通过代理模式实现的，两者会发生冲突导致事务的注解失效。
            httpServiceTransaction.saveHttpServiceConfig(requestConfig, responseConfig, httpParamConfigList);
        } catch (Exception e) {
            throw new ManagerException(e);
        }
    }

}
